<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">

          <a-col :md="4" :sm="8">
            <a-form-item label="所在区域">
              <a-select @change="(value,option) => regionHandleSelectChange(value,option)"
                        defaultValue="">
<!--                @change="regionHandleSelectChange"-->
                <a-select-option key="-1" value="">
                  全部
                </a-select-option>
                <a-select-option v-for="(regionInfo,index) in this.regionSelectOption" :key="regionInfo.num" :value="regionInfo.name">
                  {{regionInfo.name}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="楼层">
              <a-select @change="(value,option) => floorHandleSelectChange(value,option)"
                        defaultValue="">
                <a-select-option key="-1" value="">
                  全部
                </a-select-option>
                <a-select-option v-for="(floor,index) in this.floorSelectOption" :key="index" :value="floor">
                  {{floor}}层
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="门牌号">
              <a-input placeholder="输入门牌号模糊搜索" v-model="queryParam.houseNum"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="户主">
              <a-input placeholder="输入姓名模糊搜素" v-model="queryParam.userName"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="8">
            <a-form-item label="创建时间 ">
              <a-range-picker v-model="queryParam.createTimeRange" @change="onChangeRangeTime" />
            </a-form-item>
          </a-col>


          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="batchAdd" type="primary" icon="plus">批量新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('楼房')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <HousesModalEditAdd ref="modalForm" @ok="modalFormOk" v-bind:projectSelectOption="projectSelectOption" v-bind:regionSelectOption="regionSelectOption"></HousesModalEditAdd>
    <HousesModalBatchAdd ref="batchAdd" v-bind:projectSelectOption="projectSelectOption" v-bind:regionSelectOption="regionSelectOption"></HousesModalBatchAdd>

  </a-card>
</template>

<script>
import HousesModalEditAdd from './modules/HousesModalEditAdd'
import HousesModalBatchAdd from "./modules/HousesModalBatchAdd";
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile} from '@/api/manage'
import {filterObj} from '@/utils/util';
import {postAction} from "@api/manage";

export default {
  name: "HousesList",
  mixins: [JeecgListMixin],
  components: {
    HousesModalEditAdd,
    HousesModalBatchAdd
  },
  data() {
    return {
      //所属项目
      projectSelectOption:[],
      //下拉选择框：所在区域
      regionSelectOption: [],

      //下拉选择框：所在楼层
      floorSelectOption:[],


      description: '楼房管理页面',
      // 表头
      columns: [
        {
          title: '所属项目',
          align: "center",
          dataIndex: 'projectName'
        },
        {
          title: '门牌号',
          align: "center",
          dataIndex: 'houseNum'
        },
        {
          title: '楼层',
          align: "center",
          dataIndex: 'floor'
        },
        {
          title: '所在区域',
          align: "center",
          dataIndex: 'regionName'
        },
        {
          title: '户主',
          align: "center",
          dataIndex: 'userName'
        },
        {
          title: '住户数',
          align: "center",
          dataIndex: 'userNum'
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark'
        },
        {
          title: '创建人',
          align: "center",
          dataIndex: 'createUser'
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/houses/houses/list",
        delete: "/houses/houses/delete",
        deleteBatch: "/houses/houses/deleteBatch",
        exportXlsUrl: "houses/houses/exportXls",
        importExcelUrl: "houses/houses/importExcel",
        regionInfo:"houses/houses/regionInfo",
        floorInfo:"houses/houses/floorInfo",
        projectInfo:"houses/houses/projectInfo"

      },
      /*查询区域属性*/
      queryParam: {
        regionName:'',
        floor:'',
        houseNum:'',
        userName:'',
        opTime_begin: "",
        opTime_end: "",
        "type": "-1",

      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },

      //用于删除的id
      idList:[],
      deleteParams:{ids:''},

      selectedRowKeys:[],

      //查到的数据
      dataSource:[],
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
//
    this.keyupEnter()
    this.loadRegionInfo()
    this.loadFloorInfo()
    this.loadProjectInfo()

  },
  methods: {
    batchAdd(){
      this.$refs.batchAdd.visible = true;
    },
    /*加载下拉选择框：所属项目*/
    loadProjectInfo(){
      const _this = this
      getAction(this.url.projectInfo).then(function (resp){
        _this.projectSelectOption = resp.result
      })
    },
    /*加载下拉选择框：所在区域*/
    loadRegionInfo(){
      const _this = this
      getAction(this.url.regionInfo).then(function (resp){
        for(const key in resp.result){
          _this.regionSelectOption.push({num:key,name:resp.result[key]})
        }
      })
    },
    regionHandleSelectChange(value,p2){

      this.queryParam.regionName = value
    },
    /*加载下拉选择框：所在楼层*/
    loadFloorInfo(){
      const _this = this
      getAction(this.url.floorInfo).then(function (resp){
        _this.floorSelectOption = resp.result
      })
    },
    floorHandleSelectChange(value,p2){

      this.queryParam.floor = value
    },


    //新增按钮点击事件
    handleExportXls(fileName) {

      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;
      let opDesc = this.queryParam.opDesc;
      let dayTime = startTime;
      if (startTime == "") {
        this.$message.error("请选择导出开始日期");
        return
      }
      if (endTime == "") {
        this.$message.error("请选择导出结束日期");
        return
      }
      if (startTime != "" && endTime != "") {
        if (startTime != endTime) {
          this.$message.error("仅支持1天数据导出,请选择导出日期");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }


      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {...this.queryParam};
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },

    onChangeRangeTime(date, dateString) {
      this.queryParam.opTime_begin = dateString[0];
      this.queryParam.opTime_end = dateString[1];
    },

    /*展示数据*/
    loadData(arg) {

      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件

      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })

    },

    searchQuery() {
      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;

      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }

      this.loadData(1);
    },

    getQueryParams() {

      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      return filterObj(param);
    },

    /*批量删除*/
    batchDel: function () {

      this.idList=[]
      this.deleteParams={ids:''}

      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {

        // var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          // ids += this.selectionRows[a].invateuserdetailId + ",";
          this.idList.push(this.selectionRows[a].id)

        }
        console.log("批量删除："+this.idList)
        this.deleteParams.ids = this.idList + ''

        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            postAction(that.url.deleteBatch, that.deleteParams).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },

    /*单个删除*/
    handleDelete: function (invateuserdetailId) {

      this.idList=[]
      this.deleteParams={ids:''}

      this.idList.push(invateuserdetailId)
      this.deleteParams.ids = this.idList+''

      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
/*      deleteAction(that.url.delete, {id: invateuserdetailId}).then((res) => {*/
      postAction(that.url.delete,this.deleteParams).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });

    },

    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>